# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase
from collections import defaultdict


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
        def find(x):
            nonlocal fa, rank
            if fa[x] == x:
                return fa[x]
            else:
                fa[x] = find(fa[x])
                return fa[x]

        def merge(i, j):
            nonlocal fa, rank
            x = find(i)
            y = find(j)

            if rank[x] <= rank[y]:
                fa[x] = y
            else:
                fa[y] = x

            if rank[x] == rank[y] and x != y:
                rank[y] += 1

        meetings.sort(key=lambda x: x[2])

        fa = [0] * n
        rank = [1] * n

        for i in range(n):
            fa[i] = i

        merge(firstPerson, 0)
        meeting_len = len(meetings)

        index = 0
        while index < meeting_len:
            j = index
            while j + 1 < meeting_len and meetings[j + 1][2] == meetings[index][2]:
                j += 1

            for i in range(index, j + 1):
                merge(meetings[i][0], meetings[i][1])

            root = find(0)
            for i in range(index, j + 1):
                if find(meetings[i][0]) != root:
                    fa[meetings[i][0]] = meetings[i][0]
                    rank[meetings[i][0]] = 1
                if find(meetings[i][1]) != root:
                    fa[meetings[i][1]] = meetings[i][1]
                    rank[meetings[i][1]] = 1

            index = j + 1

        ans = [0]
        root = find(0)
        for i in range(1, n):
            if find(i) == root:
                ans.append(i)

        return ans


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        (4, [[3, 1, 3], [1, 2, 2], [0, 3, 3]], 3, [0, 1, 3]),
        (5, [[1, 4, 3], [0, 4, 3]], 3, [0, 1, 3, 4]),
        (6, [[1, 2, 5], [2, 3, 8], [1, 5, 10]], 1, [0, 1, 2, 3, 5]),
        (5, [[3, 4, 2], [1, 2, 1], [2, 3, 1]], 1, [0, 1, 2, 3, 4]),
        (6, [[0, 2, 1], [1, 3, 1], [4, 5, 1]], 1, [0, 1, 2, 3])
    ]

    for case_item in testcases:
        # 获取测试用的case和期待的执行结果
        input1 = case_item[0]
        input2 = case_item[1]
        input3 = case_item[2]
        expect = case_item[len(case_item) - 1]

        exec_result = solution.findAllPeople(input1, input2, input3)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)
